package cn.itsource.hrm.exception;

import cn.itsource.hrm.util.AjaxResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public AjaxResult handleException(Exception e){
        return new AjaxResult().setSuccess(false).setMessage("系统繁忙，稍后再试");
    }

    //捕获注解异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public AjaxResult MethodArgumentNotValidException(MethodArgumentNotValidException e){
        StringBuilder str = new StringBuilder();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        allErrors.forEach(objectError -> {
            str.append(objectError.getDefaultMessage()).append(" ");
        });
        return new AjaxResult().setSuccess(false).setMessage(str.toString());
    }
    //捕获自定义异常
    @ExceptionHandler(value = GlobalException.class)
    public AjaxResult handleGlobalException(GlobalException e){
        return new AjaxResult().setSuccess(false).setMessage(e.getMessage());
    }
}
